package com.songlanyun.modules.marketing.seckill.entity;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.annotation.*;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import com.songlanyun.common.drive.RootEntity;
import com.songlanyun.common.enums.MarketingConstant;
import com.songlanyun.common.enums.OrderConstant;
import com.songlanyun.common.exception.RRException;
import com.songlanyun.common.utils.DateUtils;
import com.songlanyun.common.utils.custom.ClassConvertUtils;
import com.songlanyun.common.utils.custom.DateCustomUtils;
import com.songlanyun.modules.marketing.seckill.service.SeckillActivityService;
import com.songlanyun.modules.marketing.seckill.service.SeckillActivityTimeItemService;
import com.songlanyun.modules.rabbitmq.util.SpringContextUtil;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 秒杀活动表
 *
 * @author Mark
 * @email sunlightcs@gmail.com
 * @date 2020-11-23 17:30:11
 */
@Data
@TableName("yxt_marketing_seckill_activity")
public class SeckillActivity extends RootEntity<Long, SeckillActivity> implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     *
     */
    @TableId
    private Long id;
    /**
     * 所属商家
     */
    private Long shopId;
    /**
     * 活动名称
     */
    @TableField("`name`")
    private String name;
    /**
     * 场次的开始小时数（9:00）
     */
    private String startHour;
    /**
     * 场次的结束小时数（12:00）
     */
    private String endHour;
    /**
     * 活动开始时间
     */
    @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd")
    private Date startTime;
    /**
     * 活动结束时间
     */
    @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd")
    private Date endTime;


    /**
     * 订单自动关闭时间（商品按下单减库存，请设置未付款订单自动取消时间及时释放库存，可输入3-360分钟）
     */
    private Integer closeTime;

    /**
     * 活动图片
     */
    private String imgUrl;
    /**
     * 活动说明
     */
    @TableField("`explain`")
    private String explain;
    /**
     * 是否废弃
     */
    @TableField("`discard`")
    private Boolean discard;
    /**
     *
     */
    @TableField(fill = FieldFill.INSERT)
    private Date createTime;
    /**
     *
     */
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;

    /**
     * 周期方式
     * 0：每天
     * 1：每周
     */
    private MarketingConstant.CycleMode cycleMode;

    @TableField(exist = false)
    private Integer goodsNum;

    /**
     * 周几
     */
    private String weeks;

    /**
     * 把字符串映射成对象
     */
    public void setWeeks(String weeks) {
        this.weeks = weeks;
        if (StringUtils.isEmpty(this.weeks)) {
            setWeekList(new ArrayList<>());
        } else {
            try {
                setWeekList(ClassConvertUtils.stringToClassSnake(weeks, new TypeReference<List<Integer>>() {
                }));
            } catch (IOException e) {
                throw new RRException("字符串无法转List");
            }

        }
    }

    @TableField(exist = false)
//    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private List<Integer> weekList;

    /**
     * 把对象映射为字符串
     */
    public void setWeekList(List<Integer> weekList) {
        if (MarketingConstant.CycleMode.EVERY_WEEK.equals(this.cycleMode)) {
            this.weekList = weekList;
            if (weekList.size() == 0) {
                this.weeks = "";
            } else {
                this.weeks = JSONUtil.toJsonStr(this.weekList);
            }
        }
    }

    public List<Integer> getWeekList() {
        if (StringUtils.isNotBlank(this.weeks)) {
            try {
                this.weekList = ClassConvertUtils.stringToClassSnake(this.weeks, new TypeReference<List<Integer>>() {
                });
            } catch (IOException e) {
                throw new RRException("字符串无法转List");
            }
        }

        return this.weekList;

    }

    /**
     * 把周转成字符串
     */
    @TableField(exist = false)
    private String weekTransform;

    public void loadWeekTransform() {
        if (StringUtils.isNotBlank(this.weeks)) {
            this.weekTransform = this.weeks;
            if (weeks.contains("0")) {
                this.weekTransform = weekTransform.replace("0", "日");
            }
            if (weeks.contains("1")) {
                this.weekTransform = weekTransform.replace("1", "一");
            }
            if (weeks.contains("2")) {
                this.weekTransform = weekTransform.replace("2", "二");
            }
            if (weeks.contains("3")) {
                this.weekTransform = weekTransform.replace("3", "三");
            }
            if (weeks.contains("4")) {
                this.weekTransform = weekTransform.replace("4", "四");
            }
            if (weeks.contains("5")) {
                this.weekTransform = weekTransform.replace("5", "五");
            }
            if (weeks.contains("6")) {
                this.weekTransform = weekTransform.replace("6", "六");
            }


        }
    }


    /**
     * 活动状态
     */
    @TableField(exist = false)
    private MarketingConstant.ActiveState activeState;

    /**
     * 活动状态（按每天的开始和结束）
     *
     * @return
     */
    public MarketingConstant.ActiveState getActiveState() {
        return MarketingConstant.getSeckillActiveState(this.startTime, this.endTime, this.startHour, this.endHour);
    }

    /**
     * 活动状态（从活动开始到活动结束）
     */
    @TableField(exist = false)
    private MarketingConstant.ActiveState activeTimeState;

    public void loadActiveTimeState() {
        activeTimeState = MarketingConstant.getSeckillActiveTimeState(this.startTime, this.endTime, this.startHour, this.endHour);
    }

    @TableField(exist = false)
    private List<SeckillActivityTimeItem> timeItemList;

    public List<SeckillActivityTimeItem> loadTimeItemList() {
        if (timeItemList == null) {
            SeckillActivityTimeItemService itemService = (SeckillActivityTimeItemService) SpringContextUtil.getBean("marketingSeckillActivityTimeItemService");
            timeItemList = itemService.getListBySeckillId(this.getId());
        }
        return timeItemList;
    }


    @Override
    public Long getIdentity() {
        return id;
    }

    @JsonIgnore
    public Long getPayExpireTime(Long current) {
        return this.getCloseTime() * 60 * 1000 + current;
    }
}
